<template>
  <!-- 中英文切换下拉菜单 -->
  <div class="language_box">
    <img src="@/assets/img/login/network_icon.png" alt="" />
    <el-dropdown trigger="click" @command="handleCommand" @visible-change="visibleChange">
      <span class="el-dropdown-link">
        {{ getDropdownText
        }}<i :class="['el-icon-caret-bottom', isOpen ? 'transform_open' : 'transform_close']"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="0">{{ $t('home.home10') }}</el-dropdown-item>
        <el-dropdown-item command="1">{{ $t('home.home11') }}</el-dropdown-item>
        <el-dropdown-item command="2">{{ $t('home.home36') }}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
import { messages } from '@/i18n';
import langs from '@/i18n/langs';
export default {
  data() {
    return {
      language: 'cn',
      // 控制语言切换的三角形
      isOpen: false,
    };
  },
  props: {
    // 定义切换语言的时候是否要刷新
    isRefresh: false,
  },

  computed: {
    // 获取当前下拉的值
    getDropdownText() {
      let value = '';
      if (this.language === 'cn') {
        value = this.$t('home.home10');
      } else if (this.language === 'en') {
        value = this.$t('home.home11');
      } else if (this.language === 'pt') {
        value = this.$t('home.home36');
      }
      return value;
    },
  },
  mounted() {
    let type = window.localStorage.getItem('lang');
    if (!type) {
      type = 'cn';
    }
    localStorage.setItem('lang', type);
    this.language = type;
    this.$i18n.locale = type;
  },
  methods: {
    handleCommand(command) {
      if (command === '0') {
        this.languageHandle('cn');
      } else if (command === '1') {
        this.languageHandle('en');
      } else if (command === '2') {
        // 这里需要判断是否是总后台
        let user_superAdmin = localStorage.getItem('user_superAdmin');

        if (user_superAdmin === '1') {
          this.languageHandle('en');
        } else {
          this.languageHandle('pt');
        }
      }
    },
    // 语言设置点击
    languageHandle(type) {
      this.language = type;
      localStorage.setItem('lang', type);
      this.$i18n.locale = type;
      let baseTitle = messages[type]['brand'][this.$config.labelText];
      let prefixTitle = langs[type]['login']['denglu'];
      document.title = prefixTitle + '-' + baseTitle;
      // location.reload();
      if (this.isRefresh) {
        setTimeout(() => {
          location.reload();
        }, 100);
      }
    },
    visibleChange(bool) {
      this.isOpen = bool;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-dropdown-link {
  i {
    font-size: 16px;
  }
}

img {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

.el-dropdown {
  cursor: pointer;
}
</style>